import Cookies from 'js-cookie';
import { Toast } from 'antd-mobile';
import {
  addCart as _addCart,
  fetchCartInfo,
  modifyItemNum,
  removeCartItem,
  changeCartItemSelect
} from '@/api'

export default {
  namespace: 'cart',
  state: {
    // 所有商品
    items: Cookies.get('items')
      ?
      JSON.parse(Cookies.get('items'))
      :
      [],
    // 总价格
    price: Cookies.get('price') || 0,
    // 选中商品的数量
    number: Cookies.get('number') || 0,
  },
  reducers: {
    initCart(state, { data }) {
      state.items = data.items;
      state.number = data.number;
      state.price = data.price;
      Cookies.set('items', JSON.stringify(data.items), { expires: 7 });
      Cookies.set('number', data.number, { expires: 7 });
      Cookies.set('price', data.price, { expires: 7 });
      return {
        ...state
      }
    }
  },
  effects: {
    // 加入购物车
    *addCart(action: any, { call, put }: any) {
      const res = yield call(_addCart, action.params)
      if (res.data.code === 0) {
        Toast.show('加入购物车成功')
        yield put({
          type: 'initCart',
          data: res.data.data
        })
      }
    },
    // 修改商品购买数量
    *changeItemNum(action: any, { call, put }: any) {
      const res = yield call(modifyItemNum, action.params)
      if (res.data.code === 0) {
        Toast.show('修改数量成功')
        yield put({
          type: 'initCart',
          data: res.data.data
        })
      }
    },
    // 修改商品选中状态
    *changeItemSelected(action: any, { call, put }: any) {
      const res = yield call(changeCartItemSelect, action.params)
      if (res.data.code === 0) {
        Toast.show('修改状态成功')
        yield put({
          type: 'initCart',
          data: res.data.data
        })
      }
    },
     // 删除商品
     *delItem(action: any, { call, put }: any) {
      const res = yield call(removeCartItem, action.params)
      if (res.data.code === 0) {
        Toast.show('删除商品成功')
        yield put({
          type: 'initCart',
          data: res.data.data
        })
      }
      if (res.data.code === 700) {
        Toast.show('删除商品成功')
        yield put({
          type: 'initCart',
          data: {
            items: [],
            number: 0,
            price: 0
          }
        })
      }
    },
  },
};
